// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
#include "pch.h"
#include "Logger.h"
#include "TaskExtensions.h"

using namespace Weathr;

using namespace concurrency;
using namespace Platform;

void Logger::LogInfo(Object^ sender, String^ text)
{
    OutputDebugString(L"INFO: ");
    OutputDebugString(text->Data());
    OutputDebugString(L"\n");

    // LogMessage is bindable, and therefore must be created on the ASTA thread.
    run_async_non_interactive([sender, text]()
    {
        LogMessageAdded(sender, ref new LogMessage(LogMessageKind::Info, text));
    });
}

void Logger::LogWarning(Object^ sender, String^ text)
{
    OutputDebugString(L"WARN: ");
    OutputDebugString(text->Data());
    OutputDebugString(L"\n");

    // LogMessage is bindable, and therefore must be created on the ASTA thread.
    run_async_non_interactive([sender, text]()
    {
        LogMessageAdded(sender, ref new LogMessage(LogMessageKind::Warning, text));
    });
}

void Logger::LogError(Object^ sender, String^ text)
{
    OutputDebugString(L"ERROR: ");
    OutputDebugString(text->Data());
    OutputDebugString(L"\n");

    // LogMessage is bindable, and therefore must be created on the ASTA thread.
    run_async_non_interactive([sender, text]()
    {
        LogMessageAdded(sender, ref new LogMessage(LogMessageKind::Error, text));
    });
}

task_completion_event<bool> Logger::LogAsyncAction(Object^ sender, String^ text)
{
    task_completion_event<bool> evt;
    create_task(evt).then([sender, text](bool result)
    {
        if (result)
        {
            LogInfo(sender, text + "done");
        }
        else
        {
            LogError(sender, text + "failed");
        }
    });

    // LogMessage is bindable, and therefore must be created on the ASTA thread.
    run_async_non_interactive([sender, text]()
    {
        LogMessageAdded(sender, ref new LogMessage(LogMessageKind::AsyncAction, text));
    });

    return evt;
}